package JUC;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * volatile /CAS /Atomic/blockingQueue/线程交互
 */

class MyResource{
    private volatile Boolean FLAG = true;
    AtomicInteger atomic = new AtomicInteger();
    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> b){
        this.blockingQueue = b;
    }

    public void myProduce() throws InterruptedException {
        String data = null;
        boolean success;
        while (FLAG){
            data = atomic.incrementAndGet() + "";// ++i
            success = blockingQueue.offer(data, 2L, TimeUnit.SECONDS);
            if (success){
                System.out.println(Thread.currentThread().getName() +
                        "生产了一个蛋糕，蛋糕编号为：" + data);
            } else {
                System.out.println(Thread.currentThread().getName() +
                        "生产失败");
            }
            Thread.sleep(2000);
        }
        System.out.println(Thread.currentThread().getName() +
                "被大老板叫停了，停止生产");
    }

    public void myConsume() throws InterruptedException {
        String returnValue;
        while (FLAG){
            returnValue = blockingQueue.poll(2L, TimeUnit.SECONDS);
            if (returnValue != null && returnValue.length() > 0){
                System.out.println(Thread.currentThread().getName() +
                        "消费了一个蛋糕，蛋糕编号为：" + returnValue);
            } else {
                System.out.println(Thread.currentThread().getName() +
                        "消费失败");
                return;
            }
            Thread.sleep(1000);
        }
        System.out.println(Thread.currentThread().getName() +
                "被大老板叫停了，停止消费");
    }

    // 大老板叫停
    public void stop(){
        this.FLAG = false;
    }
}

public class producer_consumer_blockQueue {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue blockingQueue = new LinkedBlockingQueue(10);
        MyResource resource = new MyResource(blockingQueue);

        new Thread(()->{
            try {
                resource.myProduce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "生产者A").start();
        new Thread(()->{
            try {
                resource.myConsume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "消费者B").start();

        Thread.sleep(5000);
        resource.stop();
    }
}
